package com.sky.controller.common;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")//swagger
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;


    //   /upload
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file) {
        log.info("要上传的文件是：{}",file.getName());

        //获取文件的原始名称，生成一个不会重复的文件名称
        //  xx.x.x.jpg
        String originalFilename = file.getOriginalFilename();
        //最后一个点的位置
        int lastIndex = originalFilename.lastIndexOf(".");
        //截取字符串
        String extension = originalFilename.substring(lastIndex);
        //生成一个不重复的名字，和后缀拼接起来
        String newFileName = UUID.randomUUID().toString() + extension;

        //开始上传
        String url = null;
        try {
            url = aliOssUtil.upload(file.getBytes(), newFileName);
            return Result.success(url);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error(e.getMessage());
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);

    }

}
